<template>
  <Dialog ref="dialogRef">
    <div style="color: #000;font-size: 20px;text-align: center;">{{displayTitle}}</div>
    <div class="password-panel">
      <div class="password-display">{{ '*'.repeat(password.length) }}</div>
      <div class="keypad">
        <button v-for="n in 9" :key="n" class="key" @click="append(n)">{{ n }}</button>
        <button class="key" @click="del">{{ $t('common.delete') }}</button>
        <button class="key" @click="append(0)">0</button>
        <button class="key" @click="confirm">{{ $t('common.confirm') }}</button>
      </div>
    </div>
  </Dialog>
	<Message ref="msgRef" />
</template>

<script setup lang="ts">
import { ref, defineExpose, defineEmits, onMounted, computed } from 'vue'
import Dialog from './Dialog.vue'
import Message from './Message.vue'

// 使用备用翻译系统
let t = (key: any) => key
let setLang = (newLang: any) => {}

// 创建响应式的翻译函数
const translationVersion = ref(0)
const $t = (key: any) => {
  // 依赖translationVersion来触发响应式更新
  translationVersion.value
  return t(key)
}

// 初始化翻译函数
const initTranslations = async () => {
  try {
    const fallback = await import('../utils/i18n-fallback')
    t = fallback.t
    setLang = (newLang: any) => {
      fallback.setLang(newLang)
      translationVersion.value++
    }
    // 监听语言变化事件
    window.addEventListener('language-changed', () => {
      translationVersion.value++
    })
  } catch (error) {
    console.warn('Failed to load i18n fallback:', error)
  }
}
const emit = defineEmits(['reset','unlock'])
const dialogRef = ref()
const password = ref('')
const newPassword = ref('')
const systemPassword = ref('')
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  rest: {
    type: Boolean,
    default: false
  }
})

// 处理标题的计算属性，支持多语言默认值
const displayTitle = computed(() => {
  return props.title || $t('components.password.defaultTitle')
})
function open() {
  dialogRef.value.open()
}
function close() {
  dialogRef.value.close()
  password.value = ''
  newPassword.value = ''
}

function getPassword() {
  return password.value
}

function clearPassword() {
  password.value = ''
  newPassword.value = ''
}
const msgRef :any= ref(null)
const append = (n: number) => {
  if (password.value.length < 10) password.value += n // 允许最多10位密码
}
const del = () => {
  password.value = password.value.slice(0, -1)
}

const confirm = () => {
  console.log('confirm 被调用，当前密码:', password.value, '系统密码:', systemPassword.value, '重置模式:', props.rest);
  
  if (!props.rest) {
    // 解锁模式
    if (password.value === systemPassword.value) {
      dialogRef.value.close()
      password.value = ''
      msgRef.value?.show($t('components.password.unlockSuccess'), 'success')
      emit('unlock')
    } else {
      msgRef.value?.show($t('components.password.passwordError'), 'error')
      password.value = ''
    }
  } else { 
    // 重置密码模式 - 发送事件给父组件处理，但不清空密码（父组件需要获取）
    console.log('发送 reset 事件，密码值:', password.value)
    emit('reset')
    // 不在这里清空密码，让父组件获取后再清空
  }
}

onMounted(async () => {
  await initTranslations()
  systemPassword.value = localStorage.getItem('systemPassword') || ''
})

// 监听 localStorage 变化
window.addEventListener('storage', (e) => {
  if (e.key === 'systemPassword') {
    systemPassword.value = e.newValue || ''
    console.log('检测到系统密码变化:', systemPassword.value)
  }
})

// 也可以监听自定义事件
window.addEventListener('password-updated', () => {
  systemPassword.value = localStorage.getItem('systemPassword') || ''
  console.log('系统密码已更新:', systemPassword.value)
})
defineExpose({ open, close, getPassword, clearPassword })
</script>

<style scoped>

.password-panel {
  margin: 24px auto 0 auto;
  width: 420px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.password-display {
  width: 100%;
  height: 64px;
  background: #f6fafd;
  border: 1.5px solid #e0e6ed;
  border-radius: 8px;
  margin-bottom: 18px;
  font-size: 22px;
  color: #333;
  letter-spacing: 8px;
  text-align: center;
  line-height: 64px;
  box-sizing: border-box;
}
.keypad {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 14px;
}
.key {
  height: 64px;
  font-size: 25px;
  border: none;
  border-radius: 8px;
  background: #eaf3fa;
  color: #333;
  cursor: pointer;
  transition: background 0.2s;
}
.key:active {
  background: #b6d6f6;
}
</style>
